<template>
	<view class="organization-detail">
		<!-- 顶部导航自定义导航栏 - 固定在图片上方 -->
		<tn-nav-bar fixed alpha customBack :bottomShadow="false" backgroundColor="none">
			<view slot="back" class='tn-custom-nav-nav-bar__back' @click="goBack">
				<text class='icon tn-icon-left'></text>
				<text class='icon tn-icon-home-capsule-fill'></text>
			</view>
		</tn-nav-bar>

		<!-- 组织头图 -->
		<view class="banner-container" v-if="organization">
			<image class="org-banner" :src="organization.banner" mode="aspectFill"></image>
			<!-- 组织头像 - 悬浮在头图底部 -->
			<image :src="organization.avatar" class="org-logo" mode="aspectFill"></image>
		</view>

		<!-- 组织基本信息 -->
		<view class="org-info" v-if="organization">
			<view class="org-title-section">
				<text class="org-name">{{ organization.name }}</text>
				<tn-tag v-if="organization.verified" type="primary" size="small" class="verified-tag">
					<text class="tn-icon-check-circle" style="font-size: 16rpx; margin-right: 4rpx;"></text>
					认证组织
				</tn-tag>
			</view>

			<view class="org-meta">
				<view class="meta-item">
					<text class="meta-label">成立时间：</text>
					<text>{{ organization.establishTime }}</text>
				</view>
				<view class="meta-item">
					<text class="meta-label">成员数量：</text>
					<text>{{ organization.memberCount }} 人</text>
				</view>
			</view>
		</view>

		<!-- 组织简介 -->
		<view class="org-section" v-if="organization">
			<view class="section-title">
				<text class="title-dot"></text>
				组织简介
			</view>
			<view class="section-content">
				<text>{{ organization.description }}</text>
			</view>
		</view>

		<!-- 组织成员 -->
		<view class="org-section" v-if="organization">
			<view class="section-title">
				<text class="title-dot"></text>
				组织成员
				<text class="view-all" @click="viewAllMembers">查看全部</text>
			</view>
			<view class="members-list">
				<!-- 会长 -->
				<view class="member-group" v-if="leaders.president.length">
					<text class="member-role-title">会长</text>
					<view class="member-items">
						<view class="member-item" v-for="(member, index) in leaders.president" :key="member.id">
							<image :src="member.avatar" class="member-avatar" mode="aspectFill"></image>
							<text class="member-name">{{ member.userName }}</text>
						</view>
					</view>
				</view>

				<!-- 副会长 -->
				<view class="member-group" v-if="leaders.vicePresident.length">
					<text class="member-role-title">副会长</text>
					<view class="member-items">
						<view class="member-item" v-for="(member, index) in leaders.vicePresident" :key="member.id">
							<image :src="member.avatar" class="member-avatar" mode="aspectFill"></image>
							<text class="member-name">{{ member.userName }}</text>
						</view>
					</view>
				</view>

				<!-- 会员 -->
				<view class="member-group" v-if="normalMembers.length">
					<text class="member-role-title">会员</text>
					<view class="member-items">
						<view class="member-item" v-for="(member, index) in normalMembers" :key="member.id">
							<image :src="member.avatar" class="member-avatar" mode="aspectFill"></image>
							<text class="member-name">{{ member.userName }}</text>
						</view>
					</view>
				</view>

				<!-- 无成员时显示 -->
				<view class="no-members" v-if="!hasAnyMembers">
					暂无成员信息
				</view>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-btn" v-if="organization">
			<view class="action-buttons">
				<view class="action-item" @click="handleLike">
					<view class="action-icon" :class="{ 'liked': isLiked }">
						<text class="tn-icon-like" :class="{ 'tn-color-red': isLiked }"></text>
					</view>
					<text class="action-text" :class="{ 'tn-color-red': isLiked }">{{ likeCount }}</text>
				</view>
				<view class="action-item" @click="handleShare">
					<view class="action-icon">
						<text class="tn-icon-share"></text>
					</view>
					<text class="action-text">分享</text>
				</view>
			</view>
			<button class="join-btn" :class="{ 'joined': isJoined }" @click="handleJoin">
				{{ isJoined ? '已加入' : '加入组织' }}
			</button>
		</view>
	</view>
</template>

<script>
	import organizationVue from './organization.vue';

	export default {
		name: 'OrganizationDetail',
		data() {
			return {
				isLiked: false,
				isJoined: false,
				likeCount: 0,
				organization: null, // 初始化为null，用于存储组织详情
				members: [] // 存储从接口获取的成员列表
			};
		},
		computed: {
			// 筛选会长和副会长
			leaders() {
				return {
					president: this.members.filter(member => member.role === 'president'),
					vicePresident: this.members.filter(member => member.role === 'vicePresident')
				};
			},
			// 筛选会员（最多显示4个）
			normalMembers() {
				return this.members
					.filter(member => member.role === 'member')
					.slice(0, 4);
			},
			// 判断是否有任何成员
			hasAnyMembers() {
				return this.leaders.president.length > 0 ||
					this.leaders.vicePresident.length > 0 ||
					this.normalMembers.length > 0;
			}
		},
		onLoad(options) {
			// 接收传递的组织ID参数
			this.organizationId = options.id;
			// 调用接口获取组织详情
			this.fetchOrganizationDetail();
			// 调用接口获取组织成员
			this.fetchTop5Members();

			// 检查本地存储的加入状态
			const localJoined = uni.getStorageSync(`org_joined_${this.organizationId}`);
			if (localJoined) {
				this.isJoined = true;
			}
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},

			// 获取组织详情数据
			async fetchOrganizationDetail() {
				try {
					// 显示加载中提示
					uni.showLoading({
						title: '加载中...'
					});

					// 调用组织详情接口
					const [err, res] = await uni.request({
						url: `http://localhost:8080/api/organization/${this.organizationId}`,
						method: 'GET'
					});

					// 关闭加载提示
					uni.hideLoading();

					if (err) {
						throw err;
					}

					// 假设接口返回格式为 {code: 200, data: {}}
					if (res.statusCode === 200 && res.data.code === 200) {
						this.organization = res.data.data;
						// 从接口数据中获取点赞数
						this.likeCount = this.organization.likeCount || 0;
						// 检查当前用户是否已点赞（如果接口返回该状态）
						if (this.organization.isLiked !== undefined) {
							this.isLiked = this.organization.isLiked;
						}
					} else {
						uni.showToast({
							title: res.data.msg || '获取组织信息失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					console.error('获取组织详情失败:', error);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				}
			},

			// 获取前5名组织成员
			async fetchTop5Members() {
				try {
					// 调用获取前5名成员接口（修正接口地址为小写）
					const [err, res] = await uni.request({
						url: `http://localhost:8080/api/organization/${this.organizationId}/Top5Members`,
						method: 'GET'
					});

					if (err) {
						throw err;
					}

					// 假设接口返回格式为 {code: 200, data: []}
					if (res.statusCode === 200 && res.data.code === 200) {
						this.members = res.data.data;
						// 打印第一个成员详情，确认数据是否正确
						console.log('第一个成员信息:', this.members[0]?.userName, this.members[0]?.avatar);
					} else {
						uni.showToast({
							title: res.data.msg || '获取成员信息失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取组织成员失败:', error);
					uni.showToast({
						title: '网络错误，成员信息加载失败',
						icon: 'none'
					});
				}
			},

			// 点赞处理
			async handleLike() {
				try {
					// 实际项目中应调用点赞接口
					const [err, res] = await uni.request({
						url: `/associations/${this.organizationId}/like`,
						method: 'POST',
						data: {
							liked: !this.isLiked
						}
					});

					if (err) {
						throw err;
					}

					if (res.statusCode === 200 && res.data.code === 200) {
						// 接口调用成功后更新本地状态
						this.isLiked = !this.isLiked;
						this.likeCount += this.isLiked ? 1 : -1;
						uni.showToast({
							title: this.isLiked ? '点赞成功' : '取消点赞',
							icon: this.isLiked ? 'success' : 'none'
						});
					} else {
						uni.showToast({
							title: res.data.msg || '操作失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('点赞操作失败:', error);
					uni.showToast({
						title: '网络错误，操作失败',
						icon: 'none'
					});
				}
			},

			// 分享处理
			handleShare() {
				uni.showToast({
					title: '分享功能开发中',
					icon: 'none'
				});
			},

			// 加入/退出组织
			async handleJoin() {
				if (this.isJoined) {
					// 退出组织
					uni.showModal({
						title: '提示',
						content: '确定要退出该组织吗？',
						success: async (res) => {
							if (res.confirm) {
								try {
									// 调用退出组织接口
									const [err, res] = await uni.request({
										url: `/associations/${this.organizationId}/quit`,
										method: 'POST'
									});

									if (err) {
										throw err;
									}

									if (res.statusCode === 200 && res.data.code === 200) {
										this.isJoined = false;
										uni.removeStorageSync(`org_joined_${this.organizationId}`);
										uni.showToast({
											title: '已退出组织',
											icon: 'none'
										});
									} else {
										uni.showToast({
											title: res.data.msg || '退出失败',
											icon: 'none'
										});
									}
								} catch (error) {
									console.error('退出组织失败:', error);
									uni.showToast({
										title: '网络错误，操作失败',
										icon: 'none'
									});
								}
							}
						}
					});
				} else {
					// 加入组织
					try {
						// 调用加入组织接口
						const [err, res] = await uni.request({
							url: `/associations/${this.organizationId}/join`,
							method: 'POST'
						});

						if (err) {
							throw err;
						}

						if (res.statusCode === 200 && res.data.code === 200) {
							this.isJoined = true;
							uni.setStorageSync(`org_joined_${this.organizationId}`, true);
							uni.showToast({
								title: '加入组织成功',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: res.data.msg || '加入失败',
								icon: 'none'
							});
						}
					} catch (error) {
						console.error('加入组织失败:', error);
						uni.showToast({
							title: '网络错误，操作失败',
							icon: 'none'
						});
					}
				}
			},

			// 查看全部成员
			viewAllMembers() {
				uni.navigateTo({
					url: `/homePages/organizationMember?id=${this.organizationId}&name=${encodeURIComponent(this.organization.name)}`
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	/* 样式部分保持不变 */
	.organization-detail {
		width: 100%;
		min-height: 100vh;
		background-color: #fff;
		padding-bottom: 160rpx;
		box-sizing: border-box;
		overflow-y: auto;
		/* 新增：内容超出时可滚动 */
		-webkit-overflow-scrolling: touch;
		/* 优化移动端滚动体验 */
	}

	/* 胶囊样式导航栏 - 与活动详情页保持一致 */
	.tn-custom-nav-bar__back {
		width: 100%;
		height: 100%;
		position: relative;
		display: flex;
		justify-content: space-evenly;
		align-items: center;
		box-sizing: border-box;
		background-color: rgba(0, 0, 0, 0.15);
		border-radius: 1000rpx;
		border: 1rpx solid rgba(255, 255, 255, 0.5);
		color: #FFFFFF;
		font-size: 18px;

		.icon {
			display: block;
			flex: 1;
			margin: auto;
			text-align: center;
		}

		&:before {
			content: " ";
			width: 1rpx;
			height: 110%;
			position: absolute;
			top: 22.5%;
			left: 0;
			right: 0;
			margin: auto;
			transform: scale(0.5);
			transform-origin: 0 0;
			pointer-events: none;
			box-sizing: border-box;
			opacity: 0.7;
			background-color: #FFFFFF;
		}
	}

	/* 头图容器 - 与活动详情页风格一致 */
	.banner-container {
		position: relative;
		width: 100%;
		height: 360rpx;
	}

	/* 组织头图样式 */
	.org-banner {
		width: 100%;
		height: 100%;
		display: block;
	}

	/* 组织头像 - 悬浮在头图底部 */
	.org-logo {
		position: absolute;
		left: 40rpx;
		bottom: -60rpx;
		width: 120rpx;
		height: 120rpx;
		border: 6rpx solid #FFFFFF;
		border-radius: 16rpx;
	}

	/* 组织基本信息样式 */
	.org-info {
		padding: 80rpx 30rpx 30rpx;
		/* 调整顶部padding为80rpx（原70rpx），确保不被120rpx高的头像遮挡 */
	}

	.org-title-section {
		display: flex;
		align-items: center;
		margin-bottom: 25rpx;
	}

	.org-name {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	.verified-tag {
		margin-left: 16rpx;
		background-color: #007AFF;
	}

	.tag-icon {
		margin-right: 4rpx;
	}

	.org-meta {
		margin-bottom: 20rpx;
	}

	.meta-item {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		color: #666;
		margin-bottom: 15rpx;
	}

	.meta-label {
		color: #999;
		margin-right: 5rpx;
	}

	/* 组织各区块通用样式 */
	.org-section {
		padding: 30rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}

	.title-dot {
		display: inline-block;
		width: 12rpx;
		height: 32rpx;
		background-color: #007AFF;
		margin-right: 15rpx;
	}

	.view-all {
		font-size: 26rpx;
		color: #007AFF;
	}

	.section-content {
		font-size: 28rpx;
		color: #666;
		line-height: 1.8;
	}

	/* 组织成员样式 */
	.members-list {
		padding: 10rpx 0;
	}

	.member-group {
		margin-bottom: 25rpx;
	}

	.member-role-title {
		font-size: 26rpx;
		color: #999;
		margin-bottom: 15rpx;
		display: block;
	}

	.member-items {
		display: flex;
		flex-wrap: wrap;
		gap: 25rpx;
		max-height: 300rpx;
		/* 限制最大高度 */
		overflow-y: auto;
		/* 超出时内部滚动 */
		padding-right: 10rpx;
		/* 避免滚动条与内容重叠 */
	}

	.member-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 100rpx;
	}

	.member-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-bottom: 10rpx;
	}

	.member-name {
		font-size: 24rpx;
		color: #333;
		text-align: center;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		width: 100%;
	}

	.no-members {
		text-align: center;
		padding: 40rpx 0;
		font-size: 28rpx;
		color: #999;
		background-color: #f9f9f9;
		border-radius: 16rpx;
	}

	/* 底部按钮样式 - 与活动详情页保持一致 */
	.bottom-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 30rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.action-buttons {
		display: flex;
		align-items: center;
		gap: 40rpx;
	}

	.action-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 10rpx 20rpx;
		border-radius: 20rpx;
		transition: all 0.3s;
	}

	.action-item:active {
		background-color: #f5f5f5;
	}

	.action-icon {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		background-color: #f8f8f8;
		margin-bottom: 10rpx;
		transition: all 0.3s;
	}

	.action-icon.liked {
		background-color: #fff0f0;
	}

	.action-text {
		font-size: 24rpx;
		color: #999;
	}

	.join-btn {
		flex: 1;
		height: 88rpx;
		line-height: 88rpx;
		background-color: #007AFF;
		color: #fff;
		font-size: 32rpx;
		border-radius: 44rpx;
		margin-left: 30rpx;
		max-width: 400rpx;
	}

	.join-btn.joined {
		background-color: #00B42A;
	}
</style>